﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Excell_On_Services.Models;
using Excell_On_Services.ViewModels;
using System.ComponentModel;
using System.Web.Security;

namespace Excell_On_Services.Controllers
{
    public class ClientController : Controller
    {

        public IEOSRepository Repository { get; set; }
        public IMembershipService MembershipService { get; set; }
        public ClientController() :this (new EFEOSRepository())
        {
        }

        public ClientController(IEOSRepository repository)
        {
            Repository = repository;
        }

        [Authorize(Roles=("Administrators"))]
        public ActionResult Search(string type,string search)
        {
            int pageIndex = 0;
            int clientPerPage = 10;

            return ShowEmployee(
                () => Repository.SearchClient(type,search,pageIndex, clientPerPage),
                () => Repository.GetClientCount(),
                pageIndex, "Index", clientPerPage
                );
        }

         
        //
        // GET: /Client/
        [Authorize(Roles = ("Administrators"))]
        public ActionResult Index([DefaultValue(0)] int pageIndex)
        {
            //int departmentsPerPage = Configuration.Instance.PostPerPage;
            
            int clientPerPage = 10;
            return ShowEmployee(
                () => Repository.FindClientsInPage(pageIndex, clientPerPage),
                () => Repository.GetClientCount(),
                pageIndex, "Index", clientPerPage
                );
        }

        [Authorize(Roles = ("Administrators"))]
        private ActionResult ShowEmployee(Func<IEnumerable<Client>> filterFunc, Func<int> countFunc, int pageIndex, string actionName, int clientPerPage)
        {
            var clients = filterFunc();
            var clientsCount = countFunc();
            var model = new ClientsDisplayModel
            {
                Clients = clients,
                PagerModel = new PagerModel
                {
                    CurrentPageIndex = pageIndex,
                    ItemsPerPage = clientPerPage,
                    TotalItems = clientsCount,
                    PageUrlTemplate = Url.Action(actionName, new { pageIndex = PagerModel.PageSymbol })

                }
            };
            return View("Index", model);
        }

        //
        // GET: /Client/Details/5
        [Authorize(Roles = ("Employee,Manager,Administrators"))]
        public ActionResult Details(Guid id)
        {
            var client = Repository.FindClientsByID(id);
            MembershipUser currentUser = Membership.Provider.GetUser(client.aspnet_Users.UserName, true);
            var model = new ClientModel
            {
                ClientID = client.ClientID,
                CompanyName = client.CompanyName,
                Description = client.Description,
                ProductDescription = client.Product_Description,
                Address = client.Address,
                Phone = client.Phone,
                Email = currentUser.Email,
            };
            return View(model);
        }

        //
        // GET: /Client/Create
        [Authorize(Roles = ("Administrators"))]
        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Client/Create

        //[HttpPost]
        //public ActionResult Create(ClientModel model)
        //{
        //    try
        //    {
        //        // TODO: Add insert logic here
        //        if (!ModelState.IsValid)
        //            return View(model);

        //        if (createStatus == MembershipCreateStatus.Success)
        //        {
        //            Roles.AddUserToRole(User.Identity.Name, "Client");
        //            var client = new Client
        //            {
        //                ClientID = Repository.GetIdByUsername(model.Username),
        //                CompanyName = model.CompanyName,
        //                Address = model.Address,
        //                Phone = model.Phone,
        //                Description = model.Description,
        //                Product_Description = model.ProductDescription
        //            };
        //            Repository.AddClient(client);
                    
        //            Repository.CommitChanges();
        //            return RedirectToAction("Details", new { id = client.ClientID });
        //        }
        //        else
        //        {
        //            return View();
        //        }
                
        //    }
        //    catch(Exception ex)
        //    {
        //        return View();
        //    }
        //}

        
        
        //
        // GET: /Client/Edit/5
        [Authorize(Roles = ("Employee,Manager,Administrators"))]
        public ActionResult Edit(Guid id)
        {
            var client = Repository.FindClientsByID(id);
            MembershipUser currentUser = Membership.Provider.GetUser(client.aspnet_Users.UserName, true);
            var model = new ClientModel
            {
                Username = client.aspnet_Users.UserName,
                ClientID = client.ClientID,
                CompanyName = client.CompanyName,
                Address = client.Address,
                Email = currentUser.Email,
                Phone = client.Phone,
                Description = client.Description,
                ProductDescription = client.Product_Description,
                IsStatus = client.isStatus
                
            };
            return View(model);
        }

        //
        // POST: /Client/Edit/5

        [HttpPost]
        [Authorize(Roles = ("Employee,Manager,Administrators"))]
        public ActionResult Edit(Guid id, ClientModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                    return View(model);
                var item = Repository.FindClientsByID(model.ClientID);
                MembershipUser currentUser = Membership.Provider.GetUser(item.aspnet_Users.UserName, true);
                item.CompanyName = model.CompanyName;
                item.Description = model.Description;
                item.Product_Description = model.ProductDescription;
                item.Phone = model.Phone;
                currentUser.Email = model.Email;
                item.Address = model.Address;
                Membership.UpdateUser(currentUser);
                Repository.CommitChanges();
                return RedirectToAction("Details", new {id = item.ClientID });
            }
            catch (Exception ex)
            {
                return View();
            }
        }

        

        //
        // GET: /Client/Delete/5
        [Authorize(Roles = ("Administrators"))]
        public ActionResult Delete(Guid id)
        {
            try
            {
                var client = Repository.FindClientsByID(id);
                return View(client);
            }
            catch (Exception)
            {
                return new EmptyResult();
                throw;
            }
        }

        //
        // POST: /Client/Delete/5
        [Authorize(Roles="Adminstrators")]
        [HttpPost]
        public ActionResult Delete(Guid id, ClientModel model)
        {
            try
            {
                // TODO: Add delete logic here
                if (Repository.DeleteClient(id))
                {
                    return RedirectToAction("Index");
                    
                }
                else
                {
                    return RedirectToAction("Details", new { id = id });
                }

            }
            catch
            {
                var client = Repository.FindClientsByID(id);
                return View(client);
            }
        }

        
    }
}
